import React, { useEffect, useState } from 'react';
import {
  Table,
  Divider,
  Modal,
  Form,
  Input,
  Select,
  Switch,
  Row,
  Col,
  Button,
  message,
  Radio,
  Tree,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton'
import MenuTree from '@/components/MenuTree'
import SearchBox from '@/components/SearchBox'
import GroupTree from './components/groupTree'
import {
  fetchManageList,
  manageSaveOrEdit,
  delManage,
  fetchOneManage,
} from '@/services/setting/manage';
import {
  fetchGroupTree,
  fetchGroups,
} from '@/services/group'

import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils'

const { confirm } = Modal;
const { Option } = Select;
const { TreeNode } = Tree;
const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '组织名称',
    dataIndex: 'groupName',
    key: 'groupName',
  },
  {
    title: '职位名称',
    dataIndex: 'positionName',
    key: 'positionName',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    render: (text) => (
      <span>
        {text == 0 ? '启用' : '锁定'}
      </span>
    ),
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
];

const Manages = props => {
  const { getFieldDecorator } = props.form;
  const { inform, radioGroup, selected } = props.role
  const [data, setColData] = useState([])
  const [record, setRecord] = useState({})
  const [treeData, setTreeData] = useState([])
  const [modalTreeKey, setModalTreeKey] = useState(null)
  const [btnType, setBtnType] = useState(null)
  // 分配\新增角色模态框
  const [isShow, setState] = useState(false)
  const [groups, setGroupList] = useState([])

  useEffect(() => {
    getList()
    fetchTree()
    groupList()
  }, [])

  // 接口请求
  const getList = async params => {
    const r = await fetchManageList(params)
    setColData(r.data)
  }
  // 机构组织列表
  const groupList = async (params = { supplierId: 1 }) => {
    const res = await fetchGroups(params)
    setGroupList(res.data)
  }
  const fetchTree = async (params={supplierType: 1}) => {
    const res = await fetchGroupTree(params)
    setTreeData(res.data)
  }


  // 新增修改
  const handleRole = async params => {
    const r = await manageSaveOrEdit(params)
    if (r.code == 0) getList()
  }

  // 查询
  const searchOneRole = async params => {
    const r = await fetchOneManage(params)
    setColData(r.data)
  }

  const removeRole = async record => {
    const res = await delManage({
      id: record.id
    })
    if (res.code == 0) {
      const index = data.findIndex(e => e.id == record.id)
      setColData(() => {
        data.splice(index, 1)
        return [...data]
      })
    }
  }

  // 业务处理
  const handleStatus = record =>  {
    setState(!isShow)
    props.dispatch({
      type: 'role/changeModelState',
      payload: {
        inform: record
      }
    })
  }

  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        let params = {}
        btnType == 1 ? 
        params = {
          ...values,
          groupId: modalTreeKey[0],
          status: !!values.status ? 0 : 1,
        } :
        params = {
          ...inform,
          ...values,
          status: !!values.status ? 0 : 1,
          groupId: modalTreeKey[0],
        }

        handleRole(params)
        setState(!isShow)
      }
    });
  };

  // 查询表单
  const getFields = () => {
    return (
      <>
        <Col span={8} >
          <Form.Item label={`职位名`}>
            {getFieldDecorator(`roleid`,{
            })(<Select
              showSearch
              filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
            >
              {data && data.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
            </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`组织名称`}>
            {getFieldDecorator(`groupid`,{
            })(<Select
              showSearch
              filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
            >
              {groups && groups.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
            </Select>)}
          </Form.Item>
        </Col>
      </>
    )
  }
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      console.log('Received values of form: ', values);
      if (!err) {
        searchOneRole({
          ...values,
          id: values.roleid,
        })
      }
    });
  }

  // 清空查询条件
  const handleReset = () => {
    props.form.resetFields();
    getList()
  };

  // 按钮逻辑
  const handleBtn = type => {
    setBtnType(type)
    if (record.length != 1 && type != 1) return message.warning('请选择一个项！');
    switch (type) {
      // 新增
      case 1:
        return handleStatus();
      case 3:
        return handleStatus(record[0]);
      // 查询
      case 2:
        return handleSearch();
      // 删除
      case 4:
        return removeRole(record[0])
      default:
        break;
    }
  };

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
  }

  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table
        columns={columns}
        dataSource={hasSearchBtn ? data : []}
        rowSelection={rowSelection}
        rowKey={record => record.id
      }
      />
      {/* 新增/修改 */}
      <Modal
        title="新增/修改"
        visible={isShow}
        onOk={handleSubmit.bind(this)}
        onCancel={() => setState(!isShow)}
        destroyOnClose
      >
         <Form {...formItemLayout}>
          <Form.Item label="职位名称">
            {getFieldDecorator('name', {
              initialValue: inform && inform.name,
              rules: [
                {
                  required: true,
                  message: '请输入职位名称',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="组织机构">
            {getFieldDecorator('groupId', {
              initialValue: inform && inform.groupId,
            })(<GroupTree 
                data={treeData}
                onSelect={id => setModalTreeKey(id)}  
                defaultSelectedKeys={[inform && String(inform.groupId)]}     
              />)}
          </Form.Item>
          <Form.Item label="状态">
            {getFieldDecorator('status', {
              initialValue: inform && !inform.status ? true : false,
              valuePropName: 'checked',
              })(<Switch />)}
          </Form.Item>
          <Form.Item label="描述">
            {getFieldDecorator('depict', {
              initialValue: inform && inform.depict,
              })(<Input />)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  )
}
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(Manages));
